package me.epet.car.utils;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import javazoom.jl.player.Player;
import java.io.ByteArrayInputStream;
import java.util.HashMap;

/**
 * 百度语音合成工具类
 * 需要替换为您自己的API Key和Secret Key
 */
public class BaiduVoiceSynthesizer {
    // 请替换为您自己的API Key和Secret Key
    private static final String APP_ID = "84180608";
    private static final String API_KEY = "JYWmSancz3t6P9yfz6flGEW9";
    private static final String SECRET_KEY = "Mq4i70Ge6bEVhJprpJ2awKh85AuIbayU";

    private AipSpeech client;
    private Player player;

    public BaiduVoiceSynthesizer() {
        // 初始化AipSpeech
        client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
    }

    /**
     * 合成语音并播放
     * @param text 要合成的文本
     */
    public void synthesizeAndPlay(String text) {
        new Thread(() -> {
            try {
                // 设置可选参数
                HashMap<String, Object> options = new HashMap<>();
                options.put("spd", 5); // 语速
                options.put("pit", 5); // 音调
                options.put("vol", 7); // 音量
                options.put("per", 0); // 发音人（0为女声）

                // 调用百度语音合成API
                TtsResponse res = client.synthesis(text, "zh", 1, options);
                byte[] data = res.getData();

                if (data != null) {
                    // 播放合成音频
                    player = new Player(new ByteArrayInputStream(data));
                    player.play();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 停止播放
     */
    public void stopPlay() {
        if (player != null) {
            player.close();
        }
    }
}